package com.example.admin.controller;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.jwt.JWT;
import com.example.admin.service.AdminService;
import com.example.xo.common.Result;
import com.example.xo.pojo.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author linzinan
 */
@RestController
@RequestMapping("admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @PostMapping("login")
    public Result login(@RequestBody Admin admin){
        Admin adminInDb=adminService.findByEmail(admin.getEmail());


        if (adminInDb==null){
            return Result.error();
        }

        String s = SecureUtil.md5(admin.getPassword());
        if (!s.equals(adminInDb.getPassword())){
            return Result.error();
        }
        //成功以后，签token
        String token = JWT.create()
                //载荷不允许放敏感信息
                //载荷开始
                //推荐必选
                .setPayload("adminId", "管理员id")
                //可选
                .setPayload("role", "管理员的角色")
                //可选
                .setPayload("name", "管理昵称")
                //载荷结束
                //key不要给出去
                .setKey("你的key".getBytes())
                .sign();
        return Result.success(token);
    }
}
